package com.fivestyle.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fivestyle.common.lang.Result;
import com.fivestyle.common.result.R;
import com.fivestyle.entity.Book;
import com.fivestyle.service.BookService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.TreeMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张代钊
 * @since 2021-08-04
 */
@RestController
@RequestMapping("/onlinebook/book")
public class BookController extends BaseController{

    @Autowired
    private BookService bookService;

//    增加图书的浏览次数
    @PutMapping("addBookVisit/{bookId}")
    @ApiOperation(value = "增加图书的浏览次数",notes = "当有用户点击进行图书详情页时，并且有用户登录，调用该接口以增加该书籍的访问次数")
    @Transactional
    public R addBookVisit(@PathVariable String bookId){
        try {
            Book book = bookService.getById(bookId);
            book.setVisit(book.getVisit()+1);
            bookService.saveOrUpdate(book);
            return R.ok().message("增加图书的浏览次数成功！").data("bookVisit",book.getVisit());

        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("增加图书的浏览次数的接口，发送的报错！");
        }
    }


//    添加图书
    @PostMapping("addBook")
    @ApiOperation(value = "添加图书",notes = "传入图书实体类进行添加")
    public R addBook(@RequestBody Book book){
        return bookService.addBook(book);
    }

//    分页获取访问量从高到低的图书
    @ApiOperation(value = "获取热门图书",notes = "分页获取访问量从高到低的图书")
    @GetMapping("maxCollectBook/{current}/{size}")
    public R maxVisitBook(@PathVariable Long current, @PathVariable Long size){
        return bookService.maxVisitBook(current,size);
    }

//    分类展示书籍列表
    @ApiOperation(value = "通过类型获取图书列表",notes = "分类展示书籍列表")
    @GetMapping("getBookListByType/{type}")
    public R getBookListByType(@PathVariable String type) {
        return bookService.getBookListByType(type);
    }

//    按书名、作者搜索书籍
    @ApiOperation(value = "搜索图书",notes = "传入bookName、authorName，按书名、作者搜索书籍")
    @PostMapping("getBookListByName")
    public R getBookListByName(@RequestBody(required = false) String json){
        return bookService.getBookListByName(json);
    }

    /**
     * 后台管理
     */

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('web:book:list')")
    public Result info(@PathVariable("id") String id) {
        Book Book = bookService.getById(id);
        Assert.notNull(Book, "找不到该图书");
        return Result.succ(Book);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('web:book:list')")
    public Result list(String author ,Integer size,Integer current ) {
        Page<Book> pageData=bookService.page(getPage(),new QueryWrapper<Book>()
                .like(StrUtil.isNotBlank(author), "author", author));
        return Result.succ(pageData);
    }

    @Transactional
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('web:book:save')")
    public Result save(@Validated @RequestBody Book Book) {
        bookService.save(Book);
        return Result.succ(Book);
    }

    @Transactional
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('web:book:update')")
    public Result update(@Validated @RequestBody Book Book) {
        bookService.updateById(Book);
        return Result.succ(Book);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('web:book:delete')")
    public Result delete(@RequestBody String[] ids) {
        bookService.removeByIds(Arrays.asList(ids));
        bookService.remove(new QueryWrapper<Book>().in("id", ids));
        return Result.succ("");
    }

    //    上传轮播图
    @PostMapping("/image")
    public Result Upimage(@RequestBody MultipartFile file) throws IOException {
        String url = ossService.bookImage(file);
        return Result.succ(url);
    }
}

